var AUTO;
(function (AUTO) {
    var AutoForm = (function () {
        function AutoForm(element, option) {
            this._opt = {
                formAction: "",
                formAjaxurl: "",
                formCols: 2,
                formFields: [],
                formValues: [],
                formCanceled: function () { },
                formSaved: function () { }
            };
            this.waitCount = 0;
            this._opt = $.extend(this._opt, option);
            this.$form = $(element);
            this.init();
            this.renderTable();
            if (this._opt.formValues.length) {
                this.writeValues();
            }
            this.bindClickEvent();
        }
        AutoForm.prototype.init = function () {
            this.$form.empty()
                .prop("action", this._opt.formAction)
                .addClass("autoForm")
                .append("<table class='autoFormTable'></table>\n                        <br>\n        <div class=\"autoFormDiv\">\n            <button type=\"button\" class=\"btn btn-warning btnCancel\">\n                <span class=\"glyphicon glyphicon-remove\"></span> \u53D6&nbsp;&nbsp;\u6D88\n            </button>\n            <button type=\"submit\" class=\"btn btn-info btnSave\">\n                <span class=\"glyphicon glyphicon-ok\"></span> \u4FDD&nbsp;&nbsp;\u5B58\n            </button>\n        </div>");
            this.$table = this.$form.find(".autoFormTable");
            this.$btnSave = this.$form.find(".btnSave");
            this.$btnCancle = this.$form.find(".btnCancel");
        };
        AutoForm.prototype.renderTable = function () {
            var scope = this;
            var content = "<tbody><tr>";
            var pos = 0;
            _.each(this._opt.formFields, function (item, idx) {
                if (item.type == "prikey") {
                    scope.appendPrikey(item);
                    return;
                }
                if ((pos + item.span) > scope._opt.formCols) {
                    content += "</tr><tr>";
                    pos = item.span;
                }
                else {
                    pos += item.span;
                }
                var sndSpan = (item.span > 1) ? item.span * 2 - 1 : 1;
                content += "<td class=\"greyTD\">" + item.title + "</td>";
                content += "<td colspan=\"" + sndSpan + "\">";
                switch (item.type) {
                    case "string":
                        content += scope.renderString(item);
                        break;
                    case "number":
                        content += scope.renderNumber(item);
                        break;
                    case "select":
                        content += scope.renderSelect(item);
                        break;
                    case "tree":
                        content += scope.renderTree(item);
                        break;
                    case "date":
                        content += scope.renderDate(item);
                        break;
                    case "month":
                        content += scope.renderMonth(item);
                        break;
                    case "year":
                        content += scope.renderYear(item);
                        break;
                }
                content += "</td>";
            });
            content += "</tr><tbody>";
            this.$table.append(content);
            this.$table.find('[data-type="date"]').datebox("nyr");
            this.$table.find('[data-type="month"]').datebox("ny");
            this.$table.find('[data-type="year"]').datebox("ny");
        };
        AutoForm.prototype.bindClickEvent = function () {
            var scope = this;
            this.$btnCancle.click(function () {
                scope._opt.formCanceled();
            });
            this.$btnSave.click(function () {
                scope.saveDate();
                if (scope._opt.formAction == "") {
                    return false;
                }
            });
        };
        AutoForm.prototype.appendPrikey = function (item) {
            this.$form.append(" <input name=\"" + item.field + "\" type=\"hidden\" value=\"\">");
        };
        AutoForm.prototype.renderString = function (item) {
            return "<input type=\"text\" data-type=\"string\" name=\"" + item.field + "\" />";
        };
        AutoForm.prototype.renderNumber = function (item) {
            return "<input type=\"number\" data-type=\"number\" name=\"" + item.field + "\" />";
        };
        AutoForm.prototype.renderOptions = function (list) {
            var content = "";
            content += '<option value="">请选择</option>';
            _.each(list, function (item) {
                content += "<option value=\"" + item["ID"] + "\">" + item["MC"] + "</option>;";
            });
            return content;
        };
        AutoForm.prototype.renderSelect = function (item) {
            var scope = this;
            var content = "<select data-type=\"select\" name=\"" + item.field + "\">";
            if (_.isString(item.addData)) {
                scope.waitCount++;
                $.ajax(item.addData, { type: 'GET', data: {}, dataType: 'json' })
                    .done(function (data) {
                    scope.$form.find("[name=" + item.field + "]").append(scope.renderOptions(data));
                    scope.waitCount--;
                });
            }
            else if (_.isArray(item.addData)) {
                content += scope.renderOptions(item.addData);
            }
            content += '</select>';
            return content;
        };
        AutoForm.prototype.renderTree = function (item) {
            var scope = this;
            var content = "<input type=\"hidden\" data-type=\"tree\" name=\"" + item.field + "\" />";
            content += "<input type=\"text\" data-type=\"tree\" data-label=\"" + item.field + "\" />";
            scope.waitCount++;
            content += ("<div class=\"formtree ztree\"></div>");
            $.ajax(item.addData, { type: 'GET', data: {}, dataType: 'json' })
                .done(function (treedata) {
                var $input = scope.$form.find("[name=" + item.field + "]")
                    .data("treedata", treedata);
                var $text = $input.next();
                var $tree = $text.next();
                var setting = {
                    data: {
                        key: { name: "NAME" },
                        simpleData: { enable: true, idKey: "ID", pIdKey: "PID" }
                    },
                    callback: {
                        onDblClick: function (event, treeId, treeNode) {
                            if (treeNode && treeNode.ISLEAF == '1') {
                                $input.val(treeNode.ID);
                                $text.val(treeNode.NAME);
                                $tree.hide();
                            }
                        }
                    }
                };
                $.fn.zTree.init($tree, setting, treedata);
                $text.click(function () {
                    $tree.show();
                });
                $input.parent().css("position", "relative");
                scope.waitCount--;
            });
            return content;
        };
        AutoForm.prototype.renderDate = function (item) {
            return "<input type=\"text\" data-type=\"date\" name=\"" + item.field + "\" />";
        };
        AutoForm.prototype.renderMonth = function (item) {
            return "<input type=\"text\" data-type=\"month\" name=\"" + item.field + "\" />";
        };
        AutoForm.prototype.renderYear = function (item) {
            return "<input type=\"text\" data-type=\"year\" name=\"" + item.field + "\" />";
        };
        AutoForm.prototype.writeValues = function () {
            var scope = this;
            if (scope._opt.formValues.length == 0) {
                return;
            }
            var row = scope._opt.formValues[0];
            if (this.waitCount > 0) {
                setTimeout(function () {
                    scope.writeValues();
                }, 500);
            }
            else {
                _.each(this._opt.formFields, function (item, idx) {
                    var $input = scope.$form.find("[name=" + item.field + "]");
                    var value = row[item.field];
                    if (item.type == "tree") {
                        var $text = $input.next();
                        var $tree = $text.next();
                        var treedata = $input.data("treedata");
                        var treenode = _.find(treedata, function (node) {
                            return node["ID"] == value;
                        });
                        $input.val(treenode.ID);
                        $text.val(treenode.NAME);
                    }
                    else {
                        $input.val(value);
                    }
                });
            }
        };
        AutoForm.prototype.saveDate = function () {
            var scope = this;
            if (this._opt.formAction == "") {
                var formdata = this.$form.serializeArray();
                $.ajax(this._opt.formAjaxurl, { type: 'POST', data: formdata, dataType: 'json' })
                    .done(function () {
                    scope._opt.formSaved();
                });
            }
            else {
                this.$form[0].submit();
            }
        };
        return AutoForm;
    }());
    AUTO.AutoForm = AutoForm;
})(AUTO || (AUTO = {}));
$.fn["autoForm"] = function (option) {
    return this.each(function () {
        new AUTO.AutoForm(this, option);
    });
};
